using KnowledgeQA.Data;
using KnowledgeQA.Services.Interfaces;
using KnowledgeQA.Services.Implementations;
using KnowledgeQA.Core.Interfaces;
using KnowledgeQA.Core.Implementations;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 配置数据库
builder.Services.AddDbContext<KnowledgeQADbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 注册服务
RegisterServices(builder.Services);

var app = builder.Build();

// Configure the HTTP request pipeline.
// 临时在开发和生产环境中都启用Swagger，方便测试
app.UseSwagger();
app.UseSwaggerUI();

if (app.Environment.IsDevelopment())
{
    // 开发环境特定配置
}
else
{
    // 只在生产环境中启用HTTPS重定向
    app.UseHttpsRedirection();
}

app.UseCors("AllowAll");

app.UseAuthorization();

app.MapControllers();

// 确保数据库已创建
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<KnowledgeQADbContext>();
    context.Database.EnsureCreated();
}

app.Run();

/// <summary>
/// 注册服务
/// </summary>
/// <param name="services">服务集合</param>
static void RegisterServices(IServiceCollection services)
{
    // 注册文档服务
    services.AddScoped<IDocumentService, DocumentService>();
    
    // 注册问答服务
    services.AddScoped<IQAService, QAService>();
    
    // 注册AI服务
    services.AddScoped<IAIService, OpenAIService>();
    
    // 注册向量服务
    services.AddScoped<IVectorService, InMemoryVectorService>();
    
    // 注册文档处理器
    services.AddScoped<IDocumentProcessor, TextDocumentProcessor>();
    services.AddScoped<IDocumentProcessor, PdfDocumentProcessor>();
    services.AddScoped<IDocumentProcessor, WordDocumentProcessor>();
    services.AddScoped<IDocumentProcessor, ExcelDocumentProcessor>();
} 